// import Fn from './fn'

const Common = {
  _decodeURIComponentForList: function(list, prop_list) {
    if (!list || !prop_list) {
      return
    }
    list.forEach(item => {
      // console.log(item, prop_list)
      prop_list.forEach(key => {
        if (item[key]) {
          item[key] = decodeURIComponent(item[key])
        }
      })
    })
  },

  _splitToArray: function(str, splitter) {
    if (!str) {
      return []
    }
    splitter = splitter || ','
    return Common._confirmArray(str.split(splitter))
  },

  // obj 不为空，且obj与defaultValue类型一致，就返回原obj，否则返回defaultValue
  _confirmValid: function(obj, defaultValue) {
    if (obj !== undefined && obj !== null && ((typeof obj) === (typeof defaultValue))) {
      return obj
    } else {
      return defaultValue
    }
  },

  _confirmValidArray: function(obj) {
    return Common._confirmValid(obj, [])
  },

  _confirmValidObj: function(obj) {
    return Common._confirmValid(obj, {})
  },

  // 如果data不是数组或空，或未定义，则设置为数组
  _confirmArray(data) {
    return Common._confirmValidArray(data)
  },
  _getDateDiffDays: function(date_start, date_end) {
    let dateSpan = date_end - date_start
    dateSpan = Math.abs(dateSpan)
    const iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
    return iDays
  },
  _formatStatus(status) {
    var str = ''
    if (status === '0') {
      str = '禁用'
    } else if (status === '1') {
      str = '启用'
    } else if (status === '2') {
      str = '删除'
    }
    return str
  },
  _getShortDate: function(date) {
    let date_str
    if (date instanceof Date) {
      date_str = Common.formatDate(date)
    } else {
      date_str = '' + date
    }
    const now_str = Common.formatDate(new Date())
    const len = date_str.length
    for (let i = 0; i < len; i++) {
      if (now_str.charAt(i) !== date_str.charAt(i)) {
        return date_str.substr(i, len - i)
      }
    }
    return date_str
  },
  _getShortTime: function(date) {
    let date_str
    if (date instanceof Date) {
      date_str = Common._formatDateTime(date)
    } else {
      date_str = '' + date
    }
    const now_str = Common._formatDateTime(new Date())
    const len = date_str.length
    for (let i = 0; i < len; i++) {
      if (now_str.charAt(i) !== date_str.charAt(i)) {
        return date_str.substr(i, len - i)
      }
    }
    return date_str
  },

  _formatDate: function(date) {
    return Common._formatDateWithFmt(date, 'yyyy-MM-dd')
  },
  _formatDateTime: function(date) {
    return Common._formatDateWithFmt(date, 'yyyy-MM-dd hh:mm:ss')
  },
  _formatDateWithFmt: function(date, fmt) {
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        const str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length))
      }
    }
    return fmt
  },

  _formatTimeStamp(timeStamp) {
    var date = new Date()
    date.setTime(timeStamp)
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? ('0' + m) : m
    var d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    var h = date.getHours()
    h = h < 10 ? ('0' + h) : h
    var minute = date.getMinutes()
    var second = date.getSeconds()
    minute = minute < 10 ? ('0' + minute) : minute
    second = second < 10 ? ('0' + second) : second
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
  },
  _formatTimeStampToDate(timeStamp) {
    var date = new Date()
    date.setTime(timeStamp)
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? ('0' + m) : m
    var d = date.getDate()
    d = d < 10 ? ('0' + d) : d

    return y + '-' + m + '-' + d
  },

  // 生成随机串
  _randomString: function(len) {
    const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1*** */
    const maxPos = $chars.length
    let pwd = ''
    for (let i = 0; i < len; i += 1) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
  },

  // 从list 中查找propkey字段值等于targetvalue的对象，然后返回该对象的propvalue
  _findInList(list, propkey, targetvalue, propvalue) {
    if (list === undefined || list === null) return ''
    for (const key in list) {
      // console.log(key)
      // console.log(list[i][propkey])
      // console.log(targetvalue + ' ? == ' + list[key][propkey] + ': ')
      if (list[key][propkey] === targetvalue) {
        return list[key][propvalue]
      }
    }
    return ''
  },

  // optionModel是保存结果的对象model，func是调用GroupAPI的函数，params是参数json对象，proplist是返回结果中代表目标字段的字段名
  _getOptionsList(that, GroupAPI, optionModel, func, params, propList, resolve, reject) {
    func = func || 'queryAll' // 调用API的指定函数
    propList = propList || 'list' // 指定获取 返回结果result下的哪个字段
    params = params || { }
    GroupAPI[func](params, 1, 999999).then(response => {
      if (response.data.data && response.data.data[propList] !== undefined) {
        // 如果result 的 名为propList 属性不为空，这取response.result的对应字段
        optionModel.list = response.data.data[propList]
      } else if (response.data.data && response.data.data.list) {
        // 默认取result的list字段
        optionModel.list = response.data.data.list
      } else if (response.data.data) {
        // 如果result 没有list 属性，这取空列表
        optionModel.list = []
      }
      optionModel.list = this._confirmValidArray(optionModel.list)
      if (resolve) {
        resolve(optionModel.list)
      }
    }).catch(res => {
      if (reject) {
        reject(res)
      }
    })
  },

  _getOptionsList_Promise(that, GroupAPI, optionModel, func, params, propList) {
    return new Promise((resolve, reject) => {
      this._getOptionsList(that, GroupAPI, optionModel, func, params, propList, resolve, reject)
    })
  },

  // optionModel是保存结果的对象model，func是调用API的函数，params是参数json对象，proplist是返回结果中代表目标字段的字段名
  _getList_Promise: function(that, API, func, params, propList, resultObj, pagingObj) {
    return new Promise((resolve, reject) => {
      this._getList(that, API, func, params, propList, resultObj, pagingObj, resolve, reject)
    })
  },

  // optionModel是保存结果的对象model，func是调用API的函数，params是参数json对象，proplist是返回结果中代表目标字段的字段名
  _getList: function(that, API, func, params, propList, resultObj, pagingObj, resolve, reject) {
    func = func || 'queryAll'
    propList = propList || 'list' // 指定获取 返回结果result下的哪个字段
    params = params || { }
    pagingObj = pagingObj || that
    const listPage = (params.page || that.listQuery.page) || 1
    const listLimit = (params.limit || that.listQuery.limit) || 10
    resultObj = resultObj || 'list'
    API[func](params, listPage, listLimit).then(response => {
      if (response.data.data && response.data.data[propList] !== undefined) {
        // 如果result 的 名为propList 属性不为空，这取response.result的对应字段
        that[resultObj] = response.data.data[propList]
        pagingObj.total = response.data.data.total
      } else if (response.data.data && response.data.data.list) {
        // 默认取result的list字段
        that[resultObj] = response.data.data.list
        if (response.data.data.total) {
          pagingObj.total = response.data.data.total
        } else {
          pagingObj.total = 0
        }
      } else if (response.data.data) {
        // 如果result 没有list 属性，这取空列表
        that[resultObj] = []
        pagingObj.total = 0
      }
      that[resultObj] = this._confirmValidArray(that[resultObj])
      // Just to simulate the time of the request
      // setTimeout(() => {
      that.listLoading = false
      // }, 1.5 * 1000)

      if (resolve) {
        resolve(that[resultObj])
      }
    }).catch(res => {
      if (reject) {
        reject(res)
      }
    })
  },

  // optionModel是保存结果的对象model，func是调用API的函数，params是参数json对象，propObject是返回结果中代表目标字段的字段名
  _getObject_Promise: function(that, API, func, params, propObject, resultID) {
    return new Promise((resolve, reject) => {
      this._getObject(that, API, func, params, propObject, resultID, resolve, reject)
    })
  },

  // optionModel是保存结果的对象model，func是调用API的函数，params是参数json对象，propObject是返回结果中代表目标字段的字段名
  _getObject: function(that, API, func, params, propObject, resultID, resolve, reject) {
    func = func || 'query'
    propObject = propObject || 'obj' // 指定获取 返回结果result下的哪个字段
    params = params || { }
    API[func](params).then(response => {
      let ret
      if (propObject !== undefined && propObject !== null && response.data.data !== null && response.data.data !== undefined && response.data.data[propObject] !== undefined) {
        // 如果result 的 名为propList 属性不为空，这取response.result的对应字段
        ret = response.data.data[propObject]
      } else if (response.data.data !== null && response.data.data !== undefined) {
        // 默认取result的list字段
        ret = response.data.data
      }

      // Just to simulate the time of the request
      // setTimeout(() => {
      that.listLoading = false
      // }, 1.5 * 1000)
      if (resultID !== null && resultID !== undefined && that[resultID] !== undefined && that[resultID] !== null) {
        that[resultID] = ret
      }

      if (resolve) {
        resolve(ret)
      }
    }).catch(res => {
      if (reject) {
        reject(res)
      }
    })
  },

  _createData_promise: function(that, API, func, temp) {
    return new Promise((resolve, reject) => {
      this._createData(that, API, func, temp, resolve, reject)
    })
  },

  _createData: function(that, API, func, temp, resolve, reject) {
    API[func](temp).then((data) => {
      if (data.data.data || (typeof data.data.data === typeof 'i am string')) {
        temp.setID(data.data.data.id)
        temp.addTime = data.data.data.addTime
        temp.updateTime = data.data.data.updateTime
      }
      that.list.unshift(temp)

      that.dialogFormVisible = false
      that.$notify({
        title: '成功',
        message: '创建成功',
        type: 'success',
        duration: 2000
      })
      if (resolve) {
        resolve(temp)
      }
    }).catch(res => {
      if (reject) {
        reject(res)
      }
    })
  },

  _getSts: function(that, API, temp) {
    API.getSts(temp).then((data) => {
      if (data.state === '10000') {
        that.sts = data.result
      }
    })
  },

  _modifyData_promise: function(that, API, func, temp, callback) {
    return new Promise((resolve, reject) => {
      this._modifyData(that, API, func, temp, callback, resolve, reject)
    })
  },

  _modifyData: function(that, API, func, temp, callback, resolve, reject) {
    const tempData = Object.assign({}, temp)
    console.log('API', API)
    console.log('_modifyData', temp)
    API[func](tempData).then((res) => {
      if (callback) {
        callback(res)
      }
      for (const v of that.list) {
        if (temp.equalsID(v)) {
          const index = that.list.indexOf(v)
          that.list.splice(index, 1, temp)
          break
        }
      }

      that.dialogFormVisible = false
      that.$notify({
        title: '成功',
        message: '更新成功',
        type: 'success',
        duration: 2000
      })

      if (resolve) {
        resolve(temp)
      }
    }).catch(res => {
      if (reject) {
        reject(res)
      }
    })
  },
  _deleteData_promise: function(that, API, func, rowindex, tmp) {
    return new Promise((resolve, reject) => {
      this._deleteData(that, API, func, rowindex, tmp, resolve, reject)
    })
  },

  _deleteData: function(that, API, func, rowindex, tmp, resolve, reject) {
    API[func](tmp).then(() => {
      that.list.splice(rowindex, 1)
      that.total = that.total - 1

      that.dialogFormVisible = false
      that.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })

      if (resolve) {
        resolve(true)
      }
    }).catch(res => {
      if (reject) {
        reject(res)
      }
    })
  },
  _notifySuccess: function(that, msg) {
    that.$notify({
      title: '成功',
      message: msg,
      type: 'success',
      duration: 2000
    })
  },
  _notifyWarning: function(that, msg) {
    that.$notify({
      title: '警告',
      message: msg,
      type: 'warning',
      duration: 2000
    })
  },
  _notifyInfo: function(that, msg) {
    that.$notify({
      title: '通知',
      message: msg,
      type: 'info',
      duration: 2000
    })
  },
  _notifyError: function(that, msg) {
    that.$notify({
      title: '错误',
      message: msg,
      type: 'error',
      duration: 2000
    })
  },

  getFirstDayOfMonth: function(date) {
    var d = new Date(date)
    d.setDate(1)
    return d
  },

  /**
   * 获取当前月的最后一天
   */
  getLastDayOfMonth: function(date) {
    var d = new Date(date)
    var nextMonth = this.addMonths(d, 1)
    var lastDay = this.addDays(nextMonth, -1)
    return lastDay
  },

  addDays: function(date, days) {
    const d = new Date(date)
    d.setTime(d.setDay(d.getDay() + days))
    return d
  },

  addMonths: function(date, months) {
    const d = new Date(date)
    d.setTime(d.setMonth(d.getMonth() + months))
    return d
  },

  formatDate: function(date, date_splitter) {
    date_splitter = date_splitter || '-'
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    return [year, month, day].map(this.formatNumber).join(date_splitter)
  },

  formatTime: function(date, date_splitter, time_splitter) {
    date_splitter = date_splitter || '-'
    time_splitter = time_splitter || ':'
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()

    return [year, month, day].map(this.formatNumber).join(date_splitter) + ' ' + [hour, minute, second].map(this.formatNumber).join(time_splitter)
  },

  formatNumber: function(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  // 分辨率等比
  power2Equalratio(w, h, box) {
    w = Number(w)
    h = Number(h)
    // isRact = false
    const canvasbox = document.getElementsByClassName(box)[0]
    // const mainContainer = document.getElementsByClassName(canvas)[0]
    let realwidth = 0
    let realheight = 0
    if (w > h) {
      realwidth = Number(canvasbox.clientWidth.toFixed(0))
      realheight = Number((canvasbox.clientWidth / (w / h)).toFixed(0))
    } else {
      realwidth = Number(((w / h) * canvasbox.clientHeight).toFixed(0))
      realheight = Number(canvasbox.clientHeight)
    }
    return {
      w: realwidth,
      h: realheight,
      W: realwidth + 'px',
      H: realheight + 'px'
      // isRact:true
    }
  },
  // 视频等比
  video2Equalratio(w, h, size) {
    let realsize = 0
    if (w > h) {
      realsize = Number((size / (w / h)).toFixed(0))
      // realsize = size / ((w / h).toFixed(3))
    } else {
      realsize = Number((size * (w / h)).toFixed(0))
      // realsize = size * ((w / h).toFixed(3))
    }
    return realsize
  },
  // 等比换算
  now2real(now, real) {
    return Number((Number(real) / Number(now)).toFixed(3))
  },
  real2now(now, real) {
    return Number((Number(now) / Number(real)).toFixed(3))
  },
  // 上舍取整
  ceilToInt(n) {
    return Number(Math.ceil(n).toFixed(0))
  },
  // 下舍取整
  floorToInt(n) {
    return Number(Math.floor(n).toFixed(0))
  },
  /**
   * 数组元素上移下移
   * @param {*当前元素下标} index
   * @param {*0：上移，1：下移} type
   * @param {*操作的数组} list
   */
  changeSort(index, type, list) {
    list.splice(type ? index : index - 1, 1, ...list.splice(type ? index + 1 : index, 1, list[type ? index : index - 1]))
  }

}

export default Common
